<template>
	<el-dialog :close-on-click-modal="false" :title="dataForm.userId ? '编辑角色' : '创建用户'" draggable width="347px" v-model="visible">
		<el-form :model="dataForm" :rules="dataRules" label-width="90px" ref="dataFormRef" v-loading="loading">
			<!-- <el-row :gutter="20"> -->
			<!-- <el-col :span="24" class="mb20"> -->
			<div v-if="!dataForm.userId" class="mb-3">
				<el-form-item :label="$t('sysuser.username')" prop="username">
					<el-input :disabled="dataForm.userId !== ''" placeholder="请输入用户名" v-model="dataForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" placeholder="请输入密码" v-model="dataForm.password"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="password1">
					<el-input type="password" placeholder="请再次输入密码" v-model="dataForm.password1"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="phone">
					<el-input placeholder="请输入手机号" v-model="dataForm.phone"></el-input>
				</el-form-item>
				<el-form-item label="填写职业" prop="occupation">
					<el-input placeholder="请输入职业" v-model="dataForm.occupation"></el-input>
				</el-form-item>
			</div>
			<el-form-item label="系统角色" prop="fixedRole">
				<el-select class="w100" clearable placeholder="请选择角色" v-model="dataForm.fixedRole">
					<el-option :key="item.roleId" :label="item.roleName" :value="item.roleId" v-for="item in roleData" />
				</el-select>
			</el-form-item>
			<el-form-item label="其他角色" prop="role">
				<el-select class="w100" multiple clearable placeholder="请选择角色" v-model="dataForm.role">
					<el-option :key="item.roleId" :label="item.roleName" :value="item.roleId" v-for="item in roleDataOther" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button class="btnClose" @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button class="btnSave" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" name="systemUserDialog" setup>
import { addObj, getObj, putObj, validatePhone, validateUsername, getRoleList } from '/@/api/admin/user';
import { list as roleList } from '/@/api/admin/role';
import { list as postList } from '/@/api/admin/post';
import { deptTree } from '/@/api/admin/dept';
// import { useDict } from '/@/hooks/dict';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { rule } from '/@/utils/validate';

const { t } = useI18n();

// 定义刷新表格emit
const emit = defineEmits(['refresh']);
// @ts-ignore
// const { lock_flag } = useDict('lock_flag');

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const deptData = ref<any[]>([]);
const roleData = ref<any[]>([]);
const roleDataOther = ref<any[]>([]);
const postData = ref<any[]>([]);
const loading = ref(false);

const dataForm = reactive({
	userId: '',
	username: '',
	password: '' as String | undefined,
	salt: '',
	lockFlag: '0',
	phone: '' as String | undefined,
	deptId: '',
	roleList: [],
	postList: [],
	fixedRole: '',
	name: '',
	email: '',
	post: [] as string[],
	role: [] as string[],
	code: '',
	status: '',
	createBy: '',
});

const dataRules = ref({
	username: [
		{ required: true, message: '用户名不能为空', trigger: 'blur' },
		{ min: 5, max: 20, message: '用户名称长度必须介于 5 和 20 之间', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				validateUsername(rule, value, callback, dataForm.userId !== '');
			},
			trigger: 'blur',
		},
	],
	password: [
		{ required: true, message: '密码不能为空', trigger: 'blur' },
		{
			min: 6,
			max: 20,
			message: '用户密码长度必须介于 6 和 20 之间',
			trigger: 'blur',
		},
	],
	password1: [
		{ required: true, message: '密码不能为空', trigger: 'blur' },
		{
			min: 6,
			max: 20,
			message: '用户密码长度必须介于 6 和 20 之间',
			trigger: 'blur',
		},
		{
			validator: (rule: any, value: any, callback: any) => {
				if (value !== dataForm.password) {
					callback(new Error('两次输入的密码不一致'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	phone: [
		{ required: true, message: '手机号不能为空', trigger: 'blur' },
		{ validator: rule.validatePhone, trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				validatePhone(rule, value, callback, dataForm.userId !== '');
			},
			trigger: 'blur',
		},
	],
	occupation: [{ required: true, message: '职业不能为空', trigger: 'blur' }],
	fixedRole: [
		{
			required: true,
			validator: (rule: any, value: any, callback: any) => {
				if (!value || value.length === 0) {
					callback(new Error('角色不能为空'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
});

// 打开弹窗
const openDialog = async () => {
	visible.value = true;

	// 重置表单数据
	Object.assign(dataForm, {
		userId: '',
		username: '',
		password: undefined,
		salt: '',
		lockFlag: '0',
		phone: undefined,
		deptId: '',
		roleList: [],
		postList: [],
		fixedRole: '',
		name: '',
		email: '',
		post: [],
		role: [],
		code: '',
		status: '',
		createBy: '',
	});

	// 重置表单验证
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
};
const editDialog = async (row: any) => {
	// 先设置数据
	Object.keys(dataForm).forEach((key) => {
		// @ts-ignore
		dataForm[key] = undefined;
	});

	Object.assign(dataForm, row);
	// 获取角色数据
	getRoleData();
	// 显示对话框
	visible.value = true;

	// 等待 DOM 更新后清除验证状态
	nextTick(() => {
		if (dataFormRef.value) {
			dataFormRef.value.clearValidate();
		}
	});
};
// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		const { userId, role, fixedRole } = dataForm;

		if (userId) {
			// 清除占位符，避免提交错误的数据
			loading.value = true;
			await putObj({ userId, role, fixedRole });
			useMessage().success('角色修改成功');
			visible.value = false; // 关闭弹窗
			emit('refresh');
		} else {
			loading.value = true;
			dataForm.role = [dataForm.role];
			await addObj(dataForm);
			useMessage().success(t('common.addSuccessText'));
			visible.value = false; // 关闭弹窗
			emit('refresh');
		}
	} catch (error: any) {
		useMessage().error(error.msg);
	} finally {
		loading.value = false;
	}
};

/**
 * 从服务器获取用户数据
 *
 * @async
 * @param {string} id - 用户 ID
 * @return {Promise} - 包含用户数据的 Promise 对象
 */
const getUserData = async (id: string) => {
	try {
		loading.value = true;
		const { data } = await getObj({ userId: id });
		Object.assign(dataForm, data);
		if (data.roleList) {
			dataForm.role = data.roleList.map((item) => item.roleId);
		}
		if (data.postList) {
			dataForm.post = data.postList.map((item) => item.postId);
		}
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化部门数据
const getDeptData = () => {
	// 获取部门数据
	deptTree().then((res) => {
		deptData.value = res.data;
		// 默认选择第一个
		dataForm.deptId = res.data[0].id;
	});
};

// 岗位数据
const getPostData = () => {
	postList().then((res) => {
		postData.value = res.data;
		// 默认选择第一个
		dataForm.post = [res.data[0].postId];
	});
};
// 角色数据
const getRoleData = () => {
	getRoleList(['ROLE_TESTER', 'ROLE_GENERAL', 'ROLE_ADMIN', 'ROLE_VIP']).then((res) => {
		roleData.value = res.data;
		// 默认选择第一个
	});

	roleList({
		excludeFixedRole: true,
	}).then((res) => {
		roleDataOther.value = res.data;
	});
};

// 暴露变量
defineExpose({
	openDialog,
	editDialog,
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item--default) {
	margin-bottom: 12px;
}
</style>
